<?php

namespace app\admin\controller;

use app\api\service\MarketingService;
use app\api\service\MemberService;
use app\common\controller\AdminBaseController;
use app\common\energyApi\JieShun;
use app\common\model\tang\BalanceLog;
use app\common\model\tang\CostType;
use app\common\model\tang\Devices;
use app\common\model\tang\Merchant;
use app\common\model\tang\MerchantEmployees as EmModel;
use think\facade\Db;
use think\Exception;

class MerchantEmployees extends AdminBaseController
{

    protected function initialize()
    {
        parent::initialize(); // TODO: Change the autogenerated stub
        $this->model = new EmModel();
    }

    public function index()
    {
        if (IS_AJAX) {
            return $this->model->getAdminPageData($this->param);
        }
        $merchant_list = getMerchant();
        //获取菜单列表
        $this->assign(compact("merchant_list"));
        return $this->fetch();
    }

    public function getRand()
    {
        $rand = mt_rand(0x00000000, 0xffffffff);// make sure we're not over 0xffffff, which shouldn't happen anyway
        $rand = dechex($rand & 0xffffffff);  // add zeroes in front of the generated string   //如果有0确保0在首位
        $rand = str_pad($rand, 8, '0', STR_PAD_LEFT);
        return $rand;
    }
    public function noaudit(){
        $id = $this->request->param('ids/d');
        $result = $this->model->where('id', $id)->update(['status' => 4]);
        if ($result) {
            return self::JsonReturn("修改成功");
        } else {
            return self::JsonReturn("修改失败", 0);
        }
    }
    /**
     * 审核
     */
    public function audit()
    {
        $id = $this->request->param('ids/d');
        $result = EmModel::where('id', $id)->find()->toArray();

        $merchInfo = (new Merchant())->find($result['merchant_id']);
        $Marketing = new MarketingService();
        $Member = new MemberService();
        Db::startTrans();
//        dd($addAdmin);
        $jieshun = new JieShun();  //personId  c93d5b66-a246-4721-ae89-a2490476f91b  //personNo  004401
        try {
            //商户宝添加员工
            if(!empty($result['marketing_role'])){
                $MarkData['username'] = $result['mobile'];
                $MarkData['password'] = 123456;
                $MarkData['sub_mch_id'] = $merchInfo['marketing_id'];
                $MarkData['mobile'] =  $result['mobile'];
                $MarkData['sex'] = 1;
                $MarkData['role_id'] = $result['marketing_role'];
                $addAdmin =$Marketing->addAdmin($MarkData);
                if(isset($addAdmin['id'])){
                    EmModel::update(['marketing_id'=>$addAdmin['id']], ['id' => $id]);
                }
            }
            if(!empty($result['member_role'])){
                //会员系统添加员工
                $memberData['store_id'] = $merchInfo['member_id'];
                $memberData['account'] = $result['mobile'];
                $memberData['staff_name'] =$result['name'];
                $memberData['phone'] =  $result['mobile'];
                $memberData['pwd'] = 123456;
                $memberData['roles'] = [$result['member_role']];
                $addMemberAdmin = $Member->save_staff($memberData);
                if (is_numeric($addMemberAdmin)) {
                    EmModel::update(['member_id'=>$addMemberAdmin,'status'=>1], ['id' => $id]);
                }
            }
            $image_data = file_get_contents($result['portrait']);
            $baseaddperson = [
                'deptId' => '0dc43e11-59c4-431f-a7e8-87e5f0d97a0d',
                'personName' => $result['name'],
                'mobile' => $result['mobile'],
                'identityNo' => $result['idcard'],
                'personPhoto' => base64_encode($image_data),
                'address' => $result['address'],
            ];
            $resoninfo = $jieshun->baseaddperson($baseaddperson);
            if ($resoninfo['code'] != 0) {
                return parent::ajaxResult([], 0, 100, $resoninfo['msg']);
            }
            $credentialNo =  $this->getRand();
            $data = [
                'cardServices' => [
                    [
                    'itemId' => $resoninfo['data']['personId'],//作为卡凭证唯一标识为 36 位 GUID
                    'deviceList' => [
                        [
                            'deviceGuid' => '88a49a0c-8e4c-40e4-ac53-0941c251bfbd',  //设备唯一标识(通过 5.3.1 查询所有控制设备获取)
                            'isDeleted' => 0  //0：默认，新增设备权限1：删除设备权限
                        ],
                        [
                            'deviceGuid' => '8b9d9b7b-2de1-4f28-84a6-1ea00aad0969',  //设备唯一标识(通过 5.3.1 查询所有控制设备获取)
                            'isDeleted' => 0  //0：默认，新增设备权限1：删除设备权限
                        ],
                        [
                            'deviceGuid' => '9350e2d8-58a8-40cb-a1f7-e6b22347d3b6',  //设备唯一标识(通过 5.3.1 查询所有控制设备获取)
                            'isDeleted' => 0  //0：默认，新增设备权限1：删除设备权限
                        ],
                        [
                            'deviceGuid' => '12abbe43-d9b0-49ab-a60b-f7ec766a2dbf',  //设备唯一标识(通过 5.3.1 查询所有控制设备获取)
                            'isDeleted' => 0  //0：默认，新增设备权限1：删除设备权限
                        ],
                        [
                            'deviceGuid' => '9ccb05c2-6d89-4d3a-bc27-ccefce9bbd46',  //设备唯一标识(通过 5.3.1 查询所有控制设备获取)
                            'isDeleted' => 0  //0：默认，新增设备权限1：删除设备权限
                        ],
                        [
                            'deviceGuid' => '22ad3de5-72aa-4050-8840-bb3901bbadc2',  //设备唯一标识(通过 5.3.1 查询所有控制设备获取)
                            'isDeleted' => 0  //0：默认，新增设备权限1：删除设备权限
                        ],
                        [
                            'deviceGuid' => '2fe1860f-1a75-48b9-9b30-7d8bf5ea4df6',  //设备唯一标识(通过 5.3.1 查询所有控制设备获取)
                            'isDeleted' => 0  //0：默认，新增设备权限1：删除设备权限
                        ],
                        [
                            'deviceGuid' => '88afa552-2cf7-4b81-8e27-9fa8a978d2b9',  //设备唯一标识(通过 5.3.1 查询所有控制设备获取)
                            'isDeleted' => 0  //0：默认，新增设备权限1：删除设备权限
                        ]
                    ],
                    'isDeleted' => 0,// 0新增1删除
                    'credentialType' => 170,//EM 卡：1MF1-A 卡：55人脸凭证：170
                    'credentialNo' =>$credentialNo,//凭证卡号需为我司发行器读出的物理卡号
                    'credentialStatus' => 'NORMAL', //NORMAL 正常  LOSSED 挂失/冻结 BACKED 注销
                    'personId' => $resoninfo['data']['personId'], //人员唯一标识，即 5.5.3 返回的 personId
                    'serviceStartDate' => date('Y-m-d H:i:s', time()),
                    'serviceEndDate' => '2030-12-12 23:59:59',
                    'week' => '1111111',
                    'cardKey' => '1234',
                    'templateData' =>base64_encode($image_data)
                ]
                ]
            ];
            $res = $jieshun->downdoorcredential($data);
            EmModel::update(['credentialNo'=>$credentialNo,'personId' =>$resoninfo['data']['personId'],'personNo'=>$resoninfo['data']['personNo'],'status'=>1], ['id' => $id]);
        if($res['code']==0){
            Db::commit();
            return self::ajaxResult([], 0, 1, '添加成功');
        }else{
            return self::ajaxResult($res,0,-1,'失败');
        }
        } catch (Exception $exception) {
            Db::rollback();
            return parent::ajaxResult([], 0, 100, $exception->getMessage());
        }
    }

    /**
     * 离职申请
     */
    public function apply()
    {
        $id = $this->request->param('ids/d');
        $jieshun = new JieShun();  //personId  c93d5b66-a246-4721-ae89-a2490476f91b  //personNo  004401
        $resultinfo = EmModel::where('id', $id)->find();
        $image_data = file_get_contents($resultinfo['portrait']);
        $data = [
            'cardServices' => [
                [
                    'itemId' => $resultinfo['personId'],//作为卡凭证唯一标识为 36 位 GUID
                    'deviceList' => [
                        [
                            'deviceGuid' => '88a49a0c-8e4c-40e4-ac53-0941c251bfbd',  //设备唯一标识(通过 5.3.1 查询所有控制设备获取)
                            'isDeleted' => 1  //0：默认，新增设备权限1：删除设备权限
                        ],
                        [
                            'deviceGuid' => '8b9d9b7b-2de1-4f28-84a6-1ea00aad0969',  //设备唯一标识(通过 5.3.1 查询所有控制设备获取)
                            'isDeleted' => 1  //0：默认，新增设备权限1：删除设备权限
                        ],
                        [
                            'deviceGuid' => '9350e2d8-58a8-40cb-a1f7-e6b22347d3b6',  //设备唯一标识(通过 5.3.1 查询所有控制设备获取)
                            'isDeleted' => 1  //0：默认，新增设备权限1：删除设备权限
                        ],
                        [
                            'deviceGuid' => '12abbe43-d9b0-49ab-a60b-f7ec766a2dbf',  //设备唯一标识(通过 5.3.1 查询所有控制设备获取)
                            'isDeleted' => 1  //0：默认，新增设备权限1：删除设备权限
                        ],
                        [
                            'deviceGuid' => '9ccb05c2-6d89-4d3a-bc27-ccefce9bbd46',  //设备唯一标识(通过 5.3.1 查询所有控制设备获取)
                            'isDeleted' => 1  //0：默认，新增设备权限1：删除设备权限
                        ],
                        [
                            'deviceGuid' => '22ad3de5-72aa-4050-8840-bb3901bbadc2',  //设备唯一标识(通过 5.3.1 查询所有控制设备获取)
                            'isDeleted' => 1  //0：默认，新增设备权限1：删除设备权限
                        ],
                        [
                            'deviceGuid' => '2fe1860f-1a75-48b9-9b30-7d8bf5ea4df6',  //设备唯一标识(通过 5.3.1 查询所有控制设备获取)
                            'isDeleted' => 1  //0：默认，新增设备权限1：删除设备权限
                        ],
                        [
                            'deviceGuid' => '88afa552-2cf7-4b81-8e27-9fa8a978d2b9',  //设备唯一标识(通过 5.3.1 查询所有控制设备获取)
                            'isDeleted' => 1  //0：默认，新增设备权限1：删除设备权限
                        ]
                    ],
                    'isDeleted' => 0,// 0新增1删除
                    'credentialType' => 170,//EM 卡：1MF1-A 卡：55人脸凭证：170
                    'credentialNo' => $resultinfo['credentialNo'],//凭证卡号需为我司发行器读出的物理卡号
                    'credentialStatus' => 'BACKED', //NORMAL 正常  LOSSED 挂失/冻结 BACKED 注销
                    'personId' => $resultinfo['personId'], //人员唯一标识，即 5.5.3 返回的 personId
                    'serviceStartDate' => date('Y-m-d H:i:s', time()),
                    'serviceEndDate' => '2030-12-12 23:59:59',
                    'week' => '1111111',
                    'cardKey' => '1234',
                    'templateData' =>base64_encode($image_data)
                ]
            ]
        ];
        $jieshun->downdoorcredential($data);
        $data1 = [
            'cardServices' => [
                [
                    'itemId' => $resultinfo['personId'],//作为卡凭证唯一标识为 36 位 GUID
                    'deviceList' => [
                        [
                            'deviceGuid' => '88a49a0c-8e4c-40e4-ac53-0941c251bfbd',  //设备唯一标识(通过 5.3.1 查询所有控制设备获取)
                            'isDeleted' => 1  //0：默认，新增设备权限1：删除设备权限
                        ],
                        [
                            'deviceGuid' => '8b9d9b7b-2de1-4f28-84a6-1ea00aad0969',  //设备唯一标识(通过 5.3.1 查询所有控制设备获取)
                            'isDeleted' => 1  //0：默认，新增设备权限1：删除设备权限
                        ],
                        [
                            'deviceGuid' => '9350e2d8-58a8-40cb-a1f7-e6b22347d3b6',  //设备唯一标识(通过 5.3.1 查询所有控制设备获取)
                            'isDeleted' => 1  //0：默认，新增设备权限1：删除设备权限
                        ],
                        [
                            'deviceGuid' => '12abbe43-d9b0-49ab-a60b-f7ec766a2dbf',  //设备唯一标识(通过 5.3.1 查询所有控制设备获取)
                            'isDeleted' => 1  //0：默认，新增设备权限1：删除设备权限
                        ],
                        [
                            'deviceGuid' => '9ccb05c2-6d89-4d3a-bc27-ccefce9bbd46',  //设备唯一标识(通过 5.3.1 查询所有控制设备获取)
                            'isDeleted' => 1  //0：默认，新增设备权限1：删除设备权限
                        ],
                        [
                            'deviceGuid' => '22ad3de5-72aa-4050-8840-bb3901bbadc2',  //设备唯一标识(通过 5.3.1 查询所有控制设备获取)
                            'isDeleted' => 1  //0：默认，新增设备权限1：删除设备权限
                        ],
                        [
                            'deviceGuid' => '2fe1860f-1a75-48b9-9b30-7d8bf5ea4df6',  //设备唯一标识(通过 5.3.1 查询所有控制设备获取)
                            'isDeleted' => 1  //0：默认，新增设备权限1：删除设备权限
                        ],
                        [
                            'deviceGuid' => '88afa552-2cf7-4b81-8e27-9fa8a978d2b9',  //设备唯一标识(通过 5.3.1 查询所有控制设备获取)
                            'isDeleted' => 1  //0：默认，新增设备权限1：删除设备权限
                        ]
                    ],
                    'isDeleted' => 1,// 0新增1删除
                    'credentialType' => 170,//EM 卡：1MF1-A 卡：55人脸凭证：170
                    'credentialNo' => $resultinfo['credentialNo'],//凭证卡号需为我司发行器读出的物理卡号
                    'credentialStatus' => 'BACKED', //NORMAL 正常  LOSSED 挂失/冻结 BACKED 注销
                    'personId' => $resultinfo['personId'], //人员唯一标识，即 5.5.3 返回的 personId
                    'serviceStartDate' => date('Y-m-d H:i:s', time()),
                    'serviceEndDate' => '2030-12-12 23:59:59',
                    'week' => '1111111',
                    'cardKey' => '1234',
                    'templateData' =>base64_encode($image_data)
                ]
            ]
        ];
        $jieshun->downdoorcredential($data1);
        $del = [
            'personId' => $resultinfo->personId
        ];
        $delJie = $jieshun->basedeleteperson($del);
        if ($delJie['code'] != 0) {
            return self::ajaxResult([], 0, -1, $delJie['msg']);
        }
        $result = EmModel::update(['status'=>-1],['id'=>$id]);
        if($result){
            return self::ajaxResult([],0,1,'离职成功');
        }else{
            return self::ajaxResult([],0,-1,'失败');
        }

    }

    /**
     * 修改登录密码
     */
    public function updatePassword()
    {
        $param = $this->request->param();
        $id = $this->request->param("id/d");//父id

        $info = $this->model->find($id)->toArray();
        if (IS_AJAX) {
            if ($info['password'] != md5($param['oldpass'])) {
                return self::JsonReturn("原密码输入错误", 0);
            }
            if (md5($param['newpassok']) != md5($param['newpass'])) {
                return self::JsonReturn("新密码和确认密码不一致", 0);
            }
            if (md5($param['newpass']) == md5($param['oldpass'])) {
                return self::JsonReturn("不能和之前密码一样", 0);
            }
            $result = $this->model->where('id', $id)->update(['password' => md5($param['newpass'])]);
            if ($result) {
                return self::JsonReturn("修改成功");
            } else {
                return self::JsonReturn("修改失败", 0);
            }

        }

        //获取菜单列表
        $this->assign('info', $info);

        return $this->fetch();
    }

    /**
     * 退费详情
     */
    public function refundDetail()
    {
        $id = $this->request->param('id/d');
        $info = EmModel::where('id', $id)->find()->toArray();
        $this->assign('info', $info);
        return $this->fetch();
    }

    /**
     * 退费
     */
    public function refund()
    {
        $param = $this->request->param();
        $refundInfo = EmModel::where('id', $param['id'])->find()->toArray();
        if ($param['type'] == 2) {//远路退回
            $result = EmModel::update(['status' => 3], ['id' => $param['id']]);
            if ($result) {
                return self::ajaxResult([], 0, 1, '离职申请成功');
            } else {
                return self::ajaxResult([], 0, -1, '失败');
            }
        } else {
            //查询设置的费包里边包含的钱,费用不可退,押金可退
            $cost = (new CostType())->where('pid', function ($query) {
                $query->table('tang_cost_type')->where(['type' => 3, 'pid' => 0])->field('id');
            })->field('cost_name,cost_money,type')->select()->toArray();
            $money = 0;
            foreach ($cost as $key => $val) {
                if ($val['type'] == 1) {
                    $money += $val['cost_money'];
                }
            }
            if ($money > $refundInfo['money']) {
                return self::ajaxResult([], 0, -1, '可退金额超出缴纳金额');
            }
            Db::startTrans();
            try {
                \app\common\model\tang\Merchant::where('id', $param['merchant_id'])->inc('balance', $money * 100)->update();
                $log['edit'] = 1;
                $log['merchant_id'] = $param['merchant_id'];
                $log['is_top_up'] = 3;
                $log['amount'] = $money * 100;
                $log['remark'] = '退还员工押金';
                (new BalanceLog())->save($log);
                EmModel::update(['status' => 3], ['id' => $param['id']]);
                Db::commit();
                return self::JsonReturn("退款成功");
            } catch (\Exception $exception) {
                Db::rollback();
                return false;
            }
        }

    }
}